import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
// import { renderWithQiankun, qiankunWindow } from "qiankun";
import { renderWithQiankun, qiankunWindow } from 'vite-plugin-qiankun/dist/helper'

import { BrowserRouter } from "react-router-dom";

let root = null;

function render(props = {}) {
  const { container } = props;
  const reactContainer = container
    ? container.querySelector("#react-root")
    : document.querySelector("#react-root");

  root = createRoot(reactContainer);
  root.render(
    <BrowserRouter
      basename={qiankunWindow.__POWERED_BY_QIANKUN__ ? "/sub-react" : "/"}
    >
      <App />
    </BrowserRouter>
  );
}

renderWithQiankun({
  mount(props) {
    render(props);
  },
  bootstrap() {
    console.log("React app bootstraped");
  },
  unmount(props) {
    const { container } = props;
    const containerElement = container
      ? container.querySelector("#react-root")
      : document.querySelector("#react-root");
    // ReactDOM.unmountComponentAtNode(root);
    if (root) {
      root.unmount(); // React 18 卸载方式
      root = null;
    } else {
      console.warn("Root is not initialized. Skipping unmount.");
    }

    // 清空 DOM 节点内容，确保沙箱干净
    if (containerElement) {
      containerElement.innerHTML = "";
    }
  },
});

if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  render();
}


